<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';
import { ElMessageBox } from 'element-plus';
import { useProjectStore } from './stores/project'

// 声明 Project 接口
interface IProject {
  id: number,
  title: string
}
const projectStore = useProjectStore()

// 选择器选中的值
const projectValue = ref<number | null>(null)

// 项目列表
const projectList = ref<IProject[]>([])

/**
 * 获取全部项目
 */
const getProject = async () => {
  const { data } = await axios.get('/api/projects')
  if (data.code === 200) {
    projectList.value = data.list
    const tempList: any = {}
    data.list.forEach((e: any) => {
      tempList[e.id] = e.title
    });
    projectStore.setList(tempList)
  } else {
    ElMessageBox({ type: 'warning', message: '请求错误。' })
  }
}

/**
 * 选择器选中事件
 */
const onChangeSltProject = () => {
  // 将选中的 ProjectId 存入 Pinia
  projectStore.setId(projectValue.value)
}

getProject()

const dialogVisible = ref(true)

const setProjectValue = (val: any) => {
  projectValue.value = val
  onChangeSltProject()
  dialogVisible.value = false
}

const onClickBtnProject = (item: IProject) => {
  setProjectValue(item.id)
}

if (projectStore.id) {
  setProjectValue(parseInt(projectStore.id))
}
</script>

<template>
  <el-container>
    <el-header>
      <el-row>
        <el-col :span="6">
          Vite Message System
        </el-col>
        <el-col :span="12">
          <nav class="nav">
            <RouterLink to="/animate">Animate</RouterLink> |
            <RouterLink to="/assets">Assets</RouterLink> |
            <RouterLink to="/runder">Runder</RouterLink> |
            <RouterLink to="/model">Model</RouterLink>
          </nav>
        </el-col>
        <el-col :span="6">
          <el-select v-model="projectValue" placeholder="Select" @change="onChangeSltProject">
            <el-option v-for="item in projectList" :key="item.id" :label="item.id + '-' + item.title" :value="item.id" />
          </el-select>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <RouterView />
    </el-main>
  </el-container>
  <el-dialog v-model="dialogVisible" title="选择项目" :show-close="false" :close-on-press-escape="false"
    :close-on-click-modal="false">
    <el-button v-for="item in projectList" :key="item.id" :value="item.id" @click="onClickBtnProject(item)">
      {{ item.id + '-' + item.title }}
    </el-button>
  </el-dialog>
</template>

<style >
html,
body {
  height: 100%;
}

#app {
  width: 100%;
  height: 100%;
}

.nav {
  text-align: left;
}
</style>
